package com.guochuang.yunwang.promanager.shiro;

import com.guochuang.yunwang.promanager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        log.info("执行doGetAuthorizationInfo方法。。");
        // 将用户的权限进行封装

        // 获取用户名
        String uid = (String) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();



        // 给该用户设置角色，角色信息存在t_role表中取
//        authorizationInfo.setRoles(userService.getRoles(username));

        // 给该用户设置权限，权限信息存在t_permission表中取
        Set<String> permissions = userService.getPermissions(Integer.parseInt(uid));

        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }



    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {



        log.info("执行doGetAuthenticationInfo方法。。");

        String uid = (String) authenticationToken.getPrincipal();

        // 把当前用户存到session中
        SecurityUtils.getSubject().getSession().setAttribute("user", uid);

        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(uid, "shiro", "myRealm");

        return authcInfo;
    }
}
